package cn.edu.xhu.library_management.user.controller.Applets;

import cn.edu.xhu.library_management.common.entity.ItemType;
import cn.edu.xhu.library_management.common.entity.R;
import cn.edu.xhu.library_management.user.client.AreaClient;

import cn.edu.xhu.library_management.user.client.BookClient;
import cn.edu.xhu.library_management.user.client.IotClient;
import cn.edu.xhu.library_management.user.entity.LmReservation;
import cn.edu.xhu.library_management.user.entity.LmReservationSeat;
import cn.edu.xhu.library_management.user.entity.dto.AreaDTO;
import cn.edu.xhu.library_management.user.entity.dto.FloorDTO;
import cn.edu.xhu.library_management.user.entity.dto.ItemNumDTO;
import cn.edu.xhu.library_management.user.entity.dto.ReservationSeatDTO;
import cn.edu.xhu.library_management.user.entity.pojo.LmArea;
import cn.edu.xhu.library_management.user.entity.pojo.LmBook;
import cn.edu.xhu.library_management.user.entity.pojo.LmFloor;
import cn.edu.xhu.library_management.user.entity.pojo.LmItemNum;
import cn.edu.xhu.library_management.user.service.LmReservationSeatService;
import cn.edu.xhu.library_management.user.service.LmReservationService;
import cn.edu.xhu.library_management.user.utils.AccountUtils;
import cn.edu.xhu.library_management.user.utils.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: MMJ
 * @Date: 2023 - 04 - 24
 * @Description: 预约座位Controller
 */
@Api(tags = "小程序模块")
@ApiSort(5)
@RestController
@RequestMapping("/lm_user/user/applet")
public class ReservationController {

    @Resource
    private AreaClient areaClient;
    @Resource
    private BookClient bookClient;

    @Resource
    private IotClient iotClient;
    @Resource
    private LmReservationSeatService reservationSeatService;



    @GetMapping("/floor")
    @ApiOperation(value = "通过图书馆Id，查询对应的楼层数量", produces = "application/json")
    public R getFloor(@RequestParam(value = "infoId") Integer infoId) {
        Map<String, Object> data = areaClient.findFloorsByType(infoId, ItemType.CHAIR.getCode()).getData();
        if (data == null) {
            return R.ok().data("floors","[]");
        }
        String floorStr = JSON.toJSONString(data.get("floors"));
        List<LmFloor> floors = JSON.parseArray(floorStr, LmFloor.class);
        List<FloorDTO> dto = new ArrayList<>();
        floors.forEach(lmFloor -> {
            FloorDTO floorDTO = new FloorDTO();
            floorDTO.setId(lmFloor.getId());
            floorDTO.setIndex(lmFloor.getIndex());
            dto.add(floorDTO);
        });
        return R.ok().data("floors",dto);
    }

    @GetMapping("/area")
    @ApiOperation(value = "通过楼层Id，获取对应的位置区域", produces = "application/json")
    public R getArea(@Param("FloorId") Integer FloorId){
        Map<String, Object> data = areaClient.findAreasByFloorId(FloorId).getData();
        if (data == null) {
            return R.ok().data("areas","[]");
        }
        String areasStr = JSON.toJSONString(data.get("areas"));
        List<LmArea> areas = JSON.parseArray(areasStr, LmArea.class);
        List<AreaDTO> dtos = new ArrayList<>();
        areas.forEach(lmArea -> {
            if (lmArea.getType()==2){
                // 只取座位
                dtos.add(new AreaDTO(lmArea.getId(), lmArea.getNumber()));
            }
        });
        return R.ok().data("areas",dtos);
    }

    @GetMapping("/seat")
    @ApiOperation(value = "通过区域Id，获取对应的座位数量", produces = "application/json")
    public R getSeat(@Param("areaId") Integer areaId){
        Map<String, Object> data = areaClient.findItemNumsByAreaId(areaId).getData();
        if (data == null) {
            return R.ok().data("seat","[]");
        }
        String seatStr = JSON.toJSONString(data.get("nums"));
        LmItemNum itemNum = JSON.parseObject(seatStr, LmItemNum.class);
        ItemNumDTO itemNumDTO = new ItemNumDTO();
        BeanUtils.copyProperties(itemNum,itemNumDTO);


        return R.ok().data("seat",itemNumDTO);
    }

    @GetMapping("/seat/reservationSeat")
    @ApiOperation(value = "获取已经预约的", produces = "application/json")
    public R reservationSeatNow(ReservationSeatDTO reservationSeat){
        // 获取已经预约的位置
        List<LmReservationSeat> seats = reservationSeatService.reservationSeatNow(reservationSeat);
       return R.ok().data("seats",seats);
    }

    @GetMapping("/myTest1/{id}")
    @ApiOperation(value = "预约座位", produces = "application/json")
    public String Test(@PathVariable("id") Integer id){
        iotClient.sendSeatInfo(id);
        return "ok";
    }

    @PostMapping("/reservationSeat")
    @ApiOperation(value = "预约座位", produces = "application/json")
    @Transactional
    public R reservationSeat(@RequestBody ReservationSeatDTO reservationSeat){
        Date nowDate = DateUtils.strCoverDate(reservationSeat.getDate(),"yyyy.MM.dd");

        // 组装对象
        LmReservationSeat lmReservationSeat = new LmReservationSeat();
        lmReservationSeat.setRsAccount(reservationSeat.getUserAccount());
        lmReservationSeat.setRsRow(reservationSeat.getSeatRow());
        lmReservationSeat.setRsColumn(reservationSeat.getSeatColumn());
        lmReservationSeat.setRsDate(nowDate);
        lmReservationSeat.setRsStatus(1); // 未就坐
        lmReservationSeat.setRsDelFlag(1); // 未删除
        lmReservationSeat.setRsInfoid(reservationSeat.getInfoId());
        lmReservationSeat.setRsFloorid(reservationSeat.getFloorId());
        lmReservationSeat.setRsAreaid(reservationSeat.getAreaId());
        boolean flag = this.reservationSeatService.save(lmReservationSeat);
        // 下发二维码
        // 获取新增Id
        QueryWrapper<LmReservationSeat> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LmReservationSeat::getRsAccount,lmReservationSeat.getRsAccount());
        queryWrapper.lambda().eq(LmReservationSeat::getRsDate,lmReservationSeat.getRsDate());
        Integer rsId = reservationSeatService.getOne(queryWrapper).getRsId();
        iotClient.sendSeatInfo(rsId);
        return flag ? R.ok("预约座位成功"):R.error("预约座位失败");
    }
    @GetMapping("/reservationSeat/seat/{id}")
    @ApiOperation(value = "就坐", produces = "application/json")
    public R seat(@PathVariable("id") Integer id){
        LmReservationSeat reservationSeat = reservationSeatService.getById(id);
        reservationSeat.setRsStatus(0); // 已经就坐
        reservationSeatService.updateById(reservationSeat);
        // 删除当前记录
        return reservationSeatService.removeById(id)?R.ok("就坐成功"):R.error("就坐失败");
    }

    @PostMapping("/reservation")
    @ApiOperation(value = "预约图书", produces = "application/json")
    public R reservationBook(@RequestBody LmReservation reservation){
        boolean flag = bookClient.reservation(reservation);
        return flag ? R.ok("预约图书成功"):R.error("请勿重复预约");
    }

    @GetMapping("/reservation")
    @ApiOperation(value = "获取预约图书记录", produces = "application/json")
    public R getReservationBook(@RequestParam("userAccount") String userAccount){
        // 获取用户预约记录
       return R.ok().data("reservationBook",bookClient.getReservationBook(userAccount));
    }

    @DeleteMapping("/reservation/{id}")
    @ApiOperation(value = "删除预约记录", produces = "application/json")
    public R delReservation(@PathVariable("id") Integer id){
        boolean flag = bookClient.delReservation(id);
        return flag ? R.ok("删除记录成功"):R.error("删除记录失败");
    }
}
